package com.qiyue.admin.auth.controller;

import com.qiyue.admin.auth.service.AuthService;
import com.qiyue.admin.auth.utils.jwt.msg.JwtAuthenticationRequest;
import com.qiyue.admin.auth.utils.jwt.msg.JwtAuthenticationResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with Intellij IDEA.
 * User : Yebinghuan
 * Created on 2018/2/10.
 * Description :
 *   服务签证 auth
 */
@RestController
@RequestMapping("jwt")
@Api("用户签证")
public class AuthController {

    @Value("${jwt.token-header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @PostMapping("token")
    @ApiOperation("登录获取签证")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody  JwtAuthenticationRequest authenticationRequest) throws Exception {
        final String token = authService.login(authenticationRequest.getAccount(), authenticationRequest.getPassword());
        return ResponseEntity.ok(new JwtAuthenticationResponse(token));
    }


    @GetMapping("refresh")
    @ApiOperation("重新获取签证")
    public ResponseEntity<?> refreshAndGetAuthenticationToken(
            HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if(refreshedToken == null) {
            return ResponseEntity.badRequest().body(null);
        } else {
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
        }
    }


    @GetMapping("verify")
    @ApiOperation("token校验")
    public ResponseEntity<?> verify(String token) throws Exception {
        authService.validate(token);
        return ResponseEntity.ok(true);
    }

    @PostMapping("invalid")
    @ApiOperation("将当前token废弃")
    public ResponseEntity<?> invalid(@RequestHeader("access-token") String token){
        authService.invalid(token);
        return ResponseEntity.ok(true);
    }
}
